package utils

import (
	"errors"
	"github.com/go-viper/mapstructure/v2"
	"reflect"
)

func StructToMap(obj interface{}) map[string]interface{} {
	result := make(map[string]interface{})
	t := reflect.TypeOf(obj)
	v := reflect.ValueOf(obj)
	// 如果是指针，取其 Elem
	if t.Kind() == reflect.Ptr {
		t = t.Elem()
		v = v.Elem()
	}
	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		value := v.Field(i)
		// 忽略未导出字段
		if field.PkgPath != "" {
			continue
		}
		result[field.Name] = value.Interface()
	}
	return result
}

func MapToStruct[T any](data map[string]interface{}) (*T, error) {
	var target T
	err := mapstructure.Decode(data, &target)
	if err != nil {
		return nil, errors.New("Format error")
	}
	return &target, nil
}
